package com.example.web.service.impl;

import com.example.web.entity.Dictionary;
import com.example.web.entity.Result;
import com.example.web.mapper.DictionaryMapper;
import com.example.web.service.DictionaryService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 字典服务实现类
 */
@Service
public class DictionaryServiceImpl implements DictionaryService {
    
    @Autowired
    private DictionaryMapper dictionaryMapper;
    
    @Override
    public Result<Map<String, Object>> getDictionaryList(String dictType, String dictName, int page, int size) {
        try {
            int offset = (page - 1) * size;
            List<Dictionary> records = dictionaryMapper.selectList(dictType, dictName, offset, size);
            int total = dictionaryMapper.selectCount(dictType, dictName);
            
            Map<String, Object> data = new HashMap<>();
            data.put("records", records);
            data.put("total", total);
            data.put("page", page);
            data.put("size", size);
            data.put("pages", (int) Math.ceil((double) total / size));
            
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("查询字典列表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Dictionary> getDictionaryById(Long id) {
        try {
            Dictionary dictionary = dictionaryMapper.selectById(id);
            if (dictionary == null) {
                return Result.error("字典不存在");
            }
            return Result.success(dictionary);
        } catch (Exception e) {
            return Result.error("查询字典失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<List<Dictionary>> getDictionaryByType(String dictType) {
        try {
            List<Dictionary> dictionaries = dictionaryMapper.selectByType(dictType);
            return Result.success(dictionaries);
        } catch (Exception e) {
            return Result.error("查询字典列表失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<String> createDictionary(Dictionary dictionary) {
        try {
            // 校验参数
            if (dictionary.getDictType() == null || dictionary.getDictType().trim().isEmpty()) {
                return Result.error("字典类型不能为空");
            }
            if (dictionary.getDictName() == null || dictionary.getDictName().trim().isEmpty()) {
                return Result.error("字典名称不能为空");
            }
            if (dictionary.getDictCode() == null || dictionary.getDictCode().trim().isEmpty()) {
                return Result.error("字典编码不能为空");
            }
            
            // 检查编码是否已存在
            int count = dictionaryMapper.checkCodeExists(dictionary.getDictCode(), null);
            if (count > 0) {
                return Result.error("字典编码已存在");
            }
            
            // 设置默认值
            if (dictionary.getSortOrder() == null) {
                dictionary.setSortOrder(0);
            }
            if (dictionary.getStatus() == null) {
                dictionary.setStatus(1);
            }
            
            int result = dictionaryMapper.insert(dictionary);
            if (result > 0) {
                return Result.success("创建成功");
            } else {
                return Result.error("创建失败");
            }
        } catch (Exception e) {
            return Result.error("创建字典失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<String> updateDictionary(Dictionary dictionary) {
        try {
            // 校验参数
            if (dictionary.getId() == null) {
                return Result.error("字典ID不能为空");
            }
            if (dictionary.getDictType() == null || dictionary.getDictType().trim().isEmpty()) {
                return Result.error("字典类型不能为空");
            }
            if (dictionary.getDictName() == null || dictionary.getDictName().trim().isEmpty()) {
                return Result.error("字典名称不能为空");
            }
            if (dictionary.getDictCode() == null || dictionary.getDictCode().trim().isEmpty()) {
                return Result.error("字典编码不能为空");
            }
            
            // 检查字典是否存在
            Dictionary existing = dictionaryMapper.selectById(dictionary.getId());
            if (existing == null) {
                return Result.error("字典不存在");
            }
            
            // 检查编码是否已被其他记录使用
            int count = dictionaryMapper.checkCodeExists(dictionary.getDictCode(), dictionary.getId());
            if (count > 0) {
                return Result.error("字典编码已存在");
            }
            
            // 设置默认值
            if (dictionary.getSortOrder() == null) {
                dictionary.setSortOrder(0);
            }
            if (dictionary.getStatus() == null) {
                dictionary.setStatus(1);
            }
            
            int result = dictionaryMapper.updateById(dictionary);
            if (result > 0) {
                return Result.success("更新成功");
            } else {
                return Result.error("更新失败");
            }
        } catch (Exception e) {
            return Result.error("更新字典失败：" + e.getMessage());
        }
    }

    @Override
    public void exportDictionary(HttpServletResponse response) {
        try {
            // 查询所有字典数据
            List<Dictionary> dictionaries = dictionaryMapper.selectList(null, null, 0, Integer.MAX_VALUE);
            
            // 创建工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("字典数据");
            
            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"字典类型", "字典名称", "字典编码", "排序", "状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                // 设置表头样式
                CellStyle style = workbook.createCellStyle();
                Font font = workbook.createFont();
                font.setBold(true);
                style.setFont(font);
                cell.setCellStyle(style);
            }
            
            // 填充数据
            AtomicInteger rowNum = new AtomicInteger(1);
            dictionaries.forEach(dict -> {
                Row row = sheet.createRow(rowNum.getAndIncrement());
                row.createCell(0).setCellValue(dict.getDictType());
                row.createCell(1).setCellValue(dict.getDictName());
                row.createCell(2).setCellValue(dict.getDictCode());
                row.createCell(3).setCellValue(dict.getSortOrder() != null ? dict.getSortOrder() : 0);
                row.createCell(4).setCellValue(dict.getStatus() == 1 ? "启用" : "禁用");
            });
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = "字典数据_" + LocalDateTime.now().toLocalDate().toString().replace("-", "") + ".xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            
            // 输出文件
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
            
        } catch (Exception e) {
            // 在异常情况下设置错误响应
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try {
                response.getWriter().write("导出失败：" + e.getMessage());
            } catch (IOException ignored) {
            }
        }
    }

    @Override
    public Result<String> importDictionary(MultipartFile file) {
        try {
            // 验证文件
            if (file.isEmpty()) {
                return Result.error("文件不能为空");
            }
            
            // 验证文件类型
            String fileName = file.getOriginalFilename();
            if (fileName == null || !fileName.endsWith(".xlsx") && !fileName.endsWith(".xls")) {
                return Result.error("请上传Excel文件（.xlsx或.xls格式）");
            }
            
            // 读取文件
            InputStream inputStream = file.getInputStream();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            
            // 解析数据
            List<Dictionary> dictionaries = new ArrayList<>();
            Iterator<Row> rowIterator = sheet.iterator();
            // 跳过表头
            if (rowIterator.hasNext()) {
                rowIterator.next();
            }
            
            while (rowIterator.hasNext()) {
                Row row = rowIterator.next();
                Dictionary dict = new Dictionary();
                
                // 字典类型
                Cell typeCell = row.getCell(0);
                if (typeCell != null) {
                    dict.setDictType(typeCell.getStringCellValue());
                }
                
                // 字典名称
                Cell nameCell = row.getCell(1);
                if (nameCell != null) {
                    dict.setDictName(nameCell.getStringCellValue());
                }
                
                // 字典编码
                Cell codeCell = row.getCell(2);
                if (codeCell != null) {
                    dict.setDictCode(codeCell.getStringCellValue());
                }
                
                // 排序
                Cell sortCell = row.getCell(3);
                if (sortCell != null) {
                    if (sortCell.getCellType() == CellType.NUMERIC) {
                        dict.setSortOrder((int) sortCell.getNumericCellValue());
                    } else {
                        try {
                            dict.setSortOrder(Integer.parseInt(sortCell.getStringCellValue()));
                        } catch (NumberFormatException ignored) {
                        }
                    }
                }
                
                // 状态
                Cell statusCell = row.getCell(4);
                if (statusCell != null) {
                    String statusStr = statusCell.getStringCellValue();
                    dict.setStatus("启用".equals(statusStr) ? 1 : 0);
                }
                
                // 基本验证
                if (dict.getDictType() != null && !dict.getDictType().trim().isEmpty() &&
                    dict.getDictName() != null && !dict.getDictName().trim().isEmpty() &&
                    dict.getDictCode() != null && !dict.getDictCode().trim().isEmpty()) {
                    dict.setCreateTime(LocalDateTime.now());
                    dict.setUpdateTime(LocalDateTime.now());
                    dictionaries.add(dict);
                }
            }
            
            // 关闭资源
            workbook.close();
            inputStream.close();
            
            // 批量导入前清空现有数据
            dictionaryMapper.deleteAll();
            
            // 批量导入
            for (Dictionary dict : dictionaries) {
                // 检查编码是否已存在（在当前批次内）
                boolean codeExists = dictionaries.stream()
                        .anyMatch(d -> d.getDictCode().equals(dict.getDictCode()) && d != dict);
                if (codeExists) {
                    continue; // 跳过重复编码的字典
                }
                dictionaryMapper.insert(dict);
            }
            
            return Result.success("导入成功，共导入" + dictionaries.size() + "条数据");
            
        } catch (Exception e) {
            return Result.error("导入失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<String> deleteDictionary(Long id) {
        try {
            if (id == null) {
                return Result.error("字典ID不能为空");
            }
            
            // 检查字典是否存在
            Dictionary existing = dictionaryMapper.selectById(id);
            if (existing == null) {
                return Result.error("字典不存在");
            }
            
            int result = dictionaryMapper.deleteById(id);
            if (result > 0) {
                return Result.success("删除成功");
            } else {
                return Result.error("删除失败");
            }
        } catch (Exception e) {
            return Result.error("删除字典失败：" + e.getMessage());
        }
    }
}